import random
import sys
import requests
import urllib
from tkinter import filedialog


class spider():
    def __init__(self, _search_term: str, _number: int) -> None:
        self.search_terms = _search_term
        self.number = _number
        self.url = 'http://image.baidu.com/search/acjson?'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT\
                     10.0; WOW64) AppleWebKit/537.36\
                      (KHTML, like Gecko) Chrome/69.0.\
                    3497.81 Safari/537.36'}
        self.headers_image = {
            'User-Agent': 'Mozilla/5.0 (Windows\
                     NT 10.0; WOW64) AppleWebKit/537.36 \
                     (KHTML, like Gecko) Chrome/69.0.\
                    3497.81 Safari/537.36',
            'Referer': 'http://image.baidu.com/\
                    search/index?tn=baiduimage&ipn=r&\
                    ct=201326592&cl=2&lm=-1&st=-1&\
                    fm=result&fr=&sf=1&fmq=1557124645631_R&\
                    pv=&ic=&nc=1&z=&hd=1&latest=0&copyright\
                    =0&se=1&showtab=0&fb=0&width=&height=\
                    &face=0&istype=2&ie=utf-8&sid=&word=%\
                    E8%83%A1%E6%AD%8C'}
        parameter_list = self.summon_parameter_list()
        urls = self.summon_urls(parameter_list)
        self.download_images(urls)

    def summon_parameter_list(self):
        model_request = 'tn=resultjson_com&ipn=rj&ct=201326592&is=&\
                fp=result&queryWord={}&cl=2&lm=-1&ie=utf-8&o\
                e=utf-8&adpicid=&st=-1&z=&ic=&hd=1&latest=0&\
                copyright=0&word={}&s=&se=&tab=&width=&height\
                =&face=0&istype=2&qc=&nc=1&fr=&expermode=&for\
                ce=&cg=star&pn={}&rn=30&gsm=78&1557125391211\
                ='
        processed_term = urllib.parse.quote(self.search_terms)
        parameter_list = \
            [model_request.format(processed_term, processed_term,_)
             for _ in range(0, self.number//30 + 1)]
        return parameter_list

    def summon_urls(self, parameter_list: list):
        page_urls = [(self.url + parameter) for parameter in parameter_list]
        image_urls = []
        for url in page_urls:
            json_data = requests.get(url, headers=self.headers).json()['data']
            for data in json_data:
                if data:
                    image_urls.append(data['thumbURL'])
        return image_urls

    def download_images(self, urls):
        file_name = filedialog.askdirectory(title="Select a directory to save.") + '/'
        print(file_name)
        random.shuffle(urls)
        for index in range(self.number):
            url = urls[index]
            with open(file_name + self.search_terms +' image_{}.jpg'.format(index + 1), 'wb') as f:
                f.write(requests.get(url, headers=self.headers_image).content)
                print('第{}张照片下载完成'.format(index + 1))
